
package Model;

import java.util.ArrayList;

/**
 * Class Customer Container represents a container for customer objects.
 * Saving, deleting and finding customers.
 */
public class CustomerContainer {

    private ArrayList<Customer> customerList;
    private static CustomerContainer instance;

    /**
     * Constructor
     * Initializes an empty database (customer list)
     */
    public CustomerContainer() {
        customerList = new ArrayList<Customer>();
    }

    /**
     * Initializes an instance of the class CustomerConatiner a.k.a. Singletone
     */
    public static CustomerContainer getInstance() {
        if (instance == null) {
            instance = new CustomerContainer();
        }
        return instance;
    }

    /**
     *A search method that returns an object of class Customer if
     * ID is identical to the parameter ID.
     * @ Param customerID
     * @ Return An object of class customer
     */
    public Customer findCustomer(int customerID) {
        Customer c = null;
        for (Customer customer : customerList) {
            if (customerID == customer.getCustomerID()) {
                c = customer;
            }
        }
        return c;
    }

    /**
     * 
     * @param customer
     * @return
     */
    public int generateID(Customer customer) {
        int newID = 1;

        if (customer.getCustomerID() == 0) {
            if (customerList.size() != 0) {
                int lastIndex = customerList.size() - 1;
                Customer lastCustomer = customerList.get(lastIndex);
                newID = lastCustomer.getCustomerID();
                newID += 1;
            }
            customer.setCustomerID(newID);
        }

        return newID;
    }

    /**
     * @param customer
     * @return
     */
    public int addCustomer(Customer customer) {
        int id = generateID(customer);
        customerList.add(customer);
        return id;
    }

    /**
     * @param customerID
     */
    public void deleteCustomer(int customerID) {
        int index = 0;
        int storeIndex = 0;
        boolean found = false;
        while (!found && index < customerList.size()) {
            if (customerList.get(index).getCustomerID() == customerID) {
                storeIndex = index;
                found = true;
            }
            index++;
        }
        customerList.remove(storeIndex);
    }
    public boolean updateCustomer(int CustomerID, String name, String address, String phone) {
        Customer e = findCustomer(CustomerID);
        if (e != null) {
            e.setName(name);
            e.setAddress(address);
            e.setPhone(phone);
            return true;
        } else {
            return false;
        }
    }
    public ArrayList<Customer> getCustomerList() {
        return customerList;
    }
    
}
